package com.mt.api.modules.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mt.api.constants.constant.Constants;
import com.mt.api.modules.domain.AppSku;
import com.mt.api.modules.manager.ISkuManager;
import com.mt.api.modules.mapper.AppSkuMapper;
import com.mt.api.util.AmountUtil;
import com.mt.api.util.SequenceBuilder;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * @Author: plover
 * @Date: 2022-01-02
 * @Description:
 */
@Component
public class SkuManagerImpl extends ServiceImpl<AppSkuMapper, AppSku> implements ISkuManager {

    @Override
    public AppSku getSkuById(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<AppSku> getListByCargoId(Integer cargoId) {
        LambdaQueryWrapper<AppSku> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AppSku::getCargoId, cargoId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public AppSku saveSkuIfNotExist(Integer cargoId, String cargoNo, String color, String size, BigDecimal retailPrice, BigDecimal wholesalePrice) {
        LambdaQueryWrapper<AppSku> skuWrapper = Wrappers.lambdaQuery();
        skuWrapper.eq(AppSku::getCargoId, cargoId)
                .eq(AppSku::getColor, color)
                .eq(AppSku::getSize, size.toUpperCase())
                .last("limit 1");
        AppSku appSku = baseMapper.selectOne(skuWrapper);
        if (Objects.isNull(appSku)) {
            SequenceBuilder builder = new SequenceBuilder();
            appSku = new AppSku();
            appSku.setCargoNo(cargoNo);
            appSku.setCargoId(cargoId);
            appSku.setColor(color);
            appSku.setSize(size);
            appSku.setSkuCode(builder.builderSkuCode());
            appSku.setSize(appSku.getSize().toUpperCase());
            appSku.setName(appSku.getCargoNo() + "-" + appSku.getColor() + "-" + appSku.getSize());
            appSku.setIsUp(Constants.SaleState.ON);
            appSku.setWarnVal(Constants.SKU_WARNVAL);
            appSku.setRetailPrice(AmountUtil.multiplyHundred(retailPrice));
            appSku.setWholesalePrice(AmountUtil.multiplyHundred(wholesalePrice));
            baseMapper.insert(appSku);
        }
        return appSku;
    }

}
